/**
 * xcx_id 诊断工具
 * 帮助检查指定xcx_id的代码包是否存在
 */

const fs = require('fs-extra');
const path = require('path');

/**
 * 诊断指定xcx_id的代码包状态
 * @param {string} xcxId 小程序托管ID
 */
async function diagnoseXcxId(xcxId) {
    console.log(`🔍 诊断小程序托管ID: ${xcxId}`);
    console.log('='.repeat(50));
    
    try {
        const codeDir = path.join(__dirname, 'code');
        
        // 1. 检查code目录是否存在
        console.log('1. 检查code目录...');
        if (!await fs.pathExists(codeDir)) {
            console.log('❌ code目录不存在');
            return false;
        }
        console.log('✅ code目录存在');
        
        // 2. 读取所有文件夹
        console.log('\n2. 读取code目录内容...');
        const folders = await fs.readdir(codeDir);
        console.log(`📁 找到 ${folders.length} 个项目:`);
        folders.forEach(folder => {
            console.log(`   - ${folder}`);
        });
        
        // 3. 查找匹配的文件夹
        console.log(`\n3. 查找匹配 xcx_id="${xcxId}" 的文件夹...`);
        const pattern = new RegExp(`^code_${xcxId}_\\d+$`);
        const matchedFolders = folders.filter(folder => pattern.test(folder));
        
        if (matchedFolders.length === 0) {
            console.log(`❌ 没有找到匹配 xcx_id="${xcxId}" 的文件夹`);
            console.log(`   期望格式: code_${xcxId}_{timestamp}`);
            return false;
        }
        
        console.log(`✅ 找到 ${matchedFolders.length} 个匹配的文件夹:`);
        matchedFolders.forEach(folder => {
            console.log(`   - ${folder}`);
        });
        
        // 4. 按时间戳排序
        console.log('\n4. 按时间戳排序...');
        matchedFolders.sort((a, b) => {
            const timestampA = parseInt(a.split('_')[2]);
            const timestampB = parseInt(b.split('_')[2]);
            return timestampB - timestampA; // 降序，最新的在前
        });
        
        const selectedFolder = matchedFolders[0];
        console.log(`🎯 选择最新的文件夹: ${selectedFolder}`);
        
        // 5. 检查内部结构
        console.log('\n5. 检查内部目录结构...');
        const selectedPath = path.join(codeDir, selectedFolder);
        const subDirs = await fs.readdir(selectedPath);
        console.log('📂 子目录:');
        subDirs.forEach(dir => {
            console.log(`   - ${dir}`);
        });
        
        // 6. 检查code目录
        console.log('\n6. 检查code目录...');
        const codePath = path.join(selectedPath, 'code');
        if (!await fs.pathExists(codePath)) {
            console.log('❌ code目录不存在');
            return false;
        }
        console.log('✅ code目录存在');
        
        // 7. 检查code内容
        console.log('\n7. 检查code内容...');
        const codeFiles = await fs.readdir(codePath);
        console.log(`📄 code目录包含 ${codeFiles.length} 个文件/文件夹:`);
        codeFiles.slice(0, 10).forEach(file => {
            console.log(`   - ${file}`);
        });
        if (codeFiles.length > 10) {
            console.log(`   ... 还有 ${codeFiles.length - 10} 个文件`);
        }
        
        // 8. 检查必要文件
        console.log('\n8. 检查必要文件...');
        const requiredFiles = ['project.config.json', 'app.json', 'common/vendor.js'];
        for (const file of requiredFiles) {
            const filePath = path.join(codePath, file);
            if (await fs.pathExists(filePath)) {
                console.log(`✅ ${file} 存在`);
            } else {
                console.log(`❌ ${file} 不存在`);
            }
        }
        
        console.log('\n✅ 诊断完成，所有检查通过！');
        return true;
        
    } catch (error) {
        console.error('❌ 诊断过程中出错:', error.message);
        return false;
    }
}

/**
 * 列出所有可用的xcx_id
 */
async function listAllXcxIds() {
    console.log('📋 列出所有可用的小程序托管ID...');
    console.log('='.repeat(50));
    
    try {
        const codeDir = path.join(__dirname, 'code');
        
        if (!await fs.pathExists(codeDir)) {
            console.log('❌ code目录不存在');
            return;
        }
        
        const folders = await fs.readdir(codeDir);
        const xcxIds = new Set();
        
        folders.forEach(folder => {
            const match = folder.match(/^code_(.+)_\d+$/);
            if (match) {
                xcxIds.add(match[1]);
            }
        });
        
        if (xcxIds.size === 0) {
            console.log('❌ 没有找到任何小程序代码包');
            return;
        }
        
        console.log(`✅ 找到 ${xcxIds.size} 个不同的小程序托管ID:`);
        Array.from(xcxIds).sort().forEach(id => {
            console.log(`   - xcx_id: ${id}`);
        });
        
        // 显示每个ID的详细信息
        console.log('\n📊 详细信息:');
        for (const id of Array.from(xcxIds).sort()) {
            const pattern = new RegExp(`^code_${id}_\\d+$`);
            const matchedFolders = folders.filter(folder => pattern.test(folder));
            
            // 找到最新的文件夹
            matchedFolders.sort((a, b) => {
                const timestampA = parseInt(a.split('_')[2]);
                const timestampB = parseInt(b.split('_')[2]);
                return timestampB - timestampA;
            });
            
            console.log(`\n🆔 xcx_id: ${id}`);
            console.log(`   📁 共 ${matchedFolders.length} 个版本`);
            console.log(`   🕐 最新版本: ${matchedFolders[0]}`);
            
            // 检查最新版本的时间
            const latestFolder = matchedFolders[0];
            const timestamp = parseInt(latestFolder.split('_')[2]);
            const date = new Date(timestamp);
            console.log(`   📅 上传时间: ${date.toLocaleString()}`);
        }
        
    } catch (error) {
        console.error('❌ 列出xcx_id时出错:', error.message);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const args = process.argv.slice(2);
    
    if (args.length === 0) {
        console.log('📖 使用方法:');
        console.log('  node debug-xcx.js <xcx_id>     # 诊断指定的xcx_id');
        console.log('  node debug-xcx.js list         # 列出所有可用的xcx_id');
        console.log('');
        console.log('📖 示例:');
        console.log('  node debug-xcx.js 8');
        console.log('  node debug-xcx.js list');
        process.exit(0);
    }
    
    const command = args[0];
    
    if (command === 'list') {
        listAllXcxIds();
    } else {
        diagnoseXcxId(command);
    }
}

module.exports = {
    diagnoseXcxId,
    listAllXcxIds
}; 